import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description TODO
 * @Author zzj
 * @Date 2020/7/22 14:46
 */
public class UserHandler {

    public void change(User src, User target, double money) {
        DBUtil util = new DBUtil();
        UserDaoImp userDao = new UserDaoImp();
        userDao.setUtil(util);
        Connection conn = util.init();
        try {
            // 设定手动事务
//            conn.setAutoCommit(false);
            util.setAutoCommit(false);
            // 修改转出
            userDao.updateMoneyById(src.getId(), -money);
            // 修改转入
            userDao.updateMoneyById(target.getId(), money);
            // 查询转出的余额
            User user = userDao.selectByPrimaryKey(src.getId());
            if (user.getMoney() < 0) {
                throw new RuntimeException("余额不足");
            }
            // commit
            conn.commit();
        } catch (Exception e) {
            try {
                // rollback
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } finally {
            // close
            util.close();
        }

    }
}
